<template>
  <div class="pricing-center">
    <div class="page-header">
      <h2>定价配置中心</h2>
      <a-space>
        <a-button type="primary" @click="openCreateModal">
          创建定价模型
        </a-button>
        <a-button @click="openPricingStrategy"> 价格策略 </a-button>
      </a-space>
    </div>

    <!-- 搜索和筛选 -->
    <a-card style="margin-bottom: 16px">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="关键词">
          <a-input
            v-model:value="searchForm.keyword"
            placeholder="搜索定价模型名称"
            style="width: 200px"
            @press-enter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="定价类型">
          <a-select
            v-model:value="searchForm.type"
            placeholder="选择类型"
            style="width: 150px"
            allow-clear
          >
            <a-select-option value="fixed">固定价格</a-select-option>
            <a-select-option value="usage">按量计费</a-select-option>
            <a-select-option value="subscription">订阅定价</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="searchForm.status"
            placeholder="选择状态"
            style="width: 120px"
            allow-clear
          >
            <a-select-option value="active">激活</a-select-option>
            <a-select-option value="draft">草稿</a-select-option>
            <a-select-option value="inactive">停用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch"> 搜索 </a-button>
            <a-button @click="handleReset"> 重置 </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 定价模型列表 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="pricingList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <a-tag :color="getTypeColor(record.type)">
              {{ getTypeLabel(record.type) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusLabel(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'customerPrice'">
            <span class="price">
              {{ record.customerPricing.currency }}
              {{ record.customerPricing.basePrice }}
            </span>
          </template>
          <template v-else-if="column.key === 'platformPrice'">
            <span class="price">
              {{ record.platformPricing.currency }}
              {{ record.platformPricing.cost }}
            </span>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a @click="viewPricing(record)">查看</a>
              <a @click="editPricing(record)">编辑</a>
              <a @click="calculatePrice(record)">计算</a>
              <a-popconfirm
                title="确定要删除这个定价模型吗？"
                @confirm="deletePricing(record.id)"
              >
                <a class="text-danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 创建/编辑定价模型模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      width="800px"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form :model="formData" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="模型名称" name="name">
              <a-input
                v-model:value="formData.name"
                placeholder="请输入模型名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="定价类型" name="type">
              <a-select
                v-model:value="formData.type"
                placeholder="选择定价类型"
              >
                <a-select-option value="fixed">固定价格</a-select-option>
                <a-select-option value="usage">按量计费</a-select-option>
                <a-select-option value="subscription">订阅定价</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="描述" name="description">
          <a-textarea v-model:value="formData.description" :rows="3" />
        </a-form-item>

        <a-divider>客户侧定价</a-divider>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="货币" name="customerCurrency">
              <a-select v-model:value="formData.customerCurrency">
                <a-select-option value="CNY">人民币 (CNY)</a-select-option>
                <a-select-option value="USD">美元 (USD)</a-select-option>
                <a-select-option value="EUR">欧元 (EUR)</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="基础价格" name="customerBasePrice">
              <a-input-number
                v-model:value="formData.customerBasePrice"
                :min="0"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="计费单位" name="customerUnit">
              <a-select v-model:value="formData.customerUnit">
                <a-select-option value="month">月</a-select-option>
                <a-select-option value="year">年</a-select-option>
                <a-select-option value="usage">使用量</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-divider>平台侧定价</a-divider>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="成本" name="platformCost">
              <a-input-number
                v-model:value="formData.platformCost"
                :min="0"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="利润率" name="platformMargin">
              <a-input-number
                v-model:value="formData.platformMargin"
                :min="0"
                :max="100"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="分润比例" name="platformRevenueShare">
              <a-input-number
                v-model:value="formData.platformRevenueShare"
                :min="0"
                :max="1"
                :step="0.1"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { message } from 'ant-design-vue';
import {
  getPricingModels,
  createPricingModel,
  updatePricingModel,
  deletePricingModel,
} from '#/api/resource-center';

// 响应式数据
const loading = ref(false);
const modalVisible = ref(false);
const isEdit = ref(false);
const currentId = ref('');

const searchForm = reactive({
  keyword: '',
  type: '',
  status: '',
});

const formData = reactive({
  name: '',
  type: '',
  description: '',
  customerCurrency: 'CNY',
  customerBasePrice: 0,
  customerUnit: 'month',
  platformCost: 0,
  platformMargin: 0,
  platformRevenueShare: 0.3,
});

const pricingList = ref([]);

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
});

const columns = [
  {
    title: '模型名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '定价类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '客户价格',
    key: 'customerPrice',
  },
  {
    title: '平台成本',
    key: 'platformPrice',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
  },
  {
    title: '操作',
    key: 'action',
    width: 300,
  },
];

// 计算属性
const modalTitle = computed(() =>
  isEdit.value ? '编辑定价模型' : '创建定价模型',
);

// 获取类型颜色
const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    fixed: 'blue',
    usage: 'green',
    subscription: 'purple',
  };
  return colorMap[type] || 'default';
};

// 获取类型标签
const getTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    fixed: '固定价格',
    usage: '按量计费',
    subscription: '订阅定价',
  };
  return labelMap[type] || type;
};

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    active: 'green',
    draft: 'orange',
    inactive: 'red',
  };
  return colorMap[status] || 'default';
};

// 获取状态标签
const getStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    active: '激活',
    draft: '草稿',
    inactive: '停用',
  };
  return labelMap[status] || status;
};

// 加载定价模型列表
const loadPricingList = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm,
    };

    const result = await getPricingModels(params);
    pricingList.value = result.items || [];
    pagination.total = result.total || 0;
  } catch (error) {
    message.error('加载定价模型列表失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadPricingList();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    type: '',
    status: '',
  });
  pagination.current = 1;
  loadPricingList();
};

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadPricingList();
};

// 打开创建模态框
const openCreateModal = () => {
  isEdit.value = false;
  currentId.value = '';
  resetForm();
  modalVisible.value = true;
};

// 编辑定价模型
const editPricing = (record: any) => {
  isEdit.value = true;
  currentId.value = record.id;
  modalVisible.value = true;

  Object.assign(formData, {
    name: record.name,
    type: record.type,
    description: record.description,
    customerCurrency: record.customerPricing.currency,
    customerBasePrice: record.customerPricing.basePrice,
    customerUnit: record.customerPricing.unit,
    platformCost: record.platformPricing.cost,
    platformMargin: record.platformPricing.margin,
    platformRevenueShare: record.platformPricing.revenueShare,
  });
};

// 查看定价模型
const viewPricing = (record: any) => {
  message.info(`查看定价模型: ${record.name}`);
};

// 计算价格
const calculatePrice = (record: any) => {
  message.info(`计算价格: ${record.name}`);
};

// 打开价格策略
const openPricingStrategy = () => {
  message.info('打开价格策略管理');
};

// 删除定价模型
const deletePricing = async (id: string) => {
  try {
    await deletePricingModel(id);
    message.success('删除成功');
    loadPricingList();
  } catch (error) {
    message.error('删除失败');
    console.error(error);
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    const pricingData = {
      name: formData.name,
      type: formData.type,
      description: formData.description,
      customerPricing: {
        currency: formData.customerCurrency,
        basePrice: formData.customerBasePrice,
        unit: formData.customerUnit,
      },
      platformPricing: {
        cost: formData.platformCost,
        margin: formData.platformMargin,
        revenueShare: formData.platformRevenueShare,
      },
    };

    if (isEdit.value) {
      await updatePricingModel(currentId.value, pricingData);
      message.success('更新成功');
      modalVisible.value = false;
      loadPricingList();
    } else {
      await createPricingModel(pricingData);
      message.success('创建成功');
      modalVisible.value = false;
      loadPricingList();
    }
  } catch (error) {
    message.error('操作失败');
    console.error(error);
  }
};

// 取消
const handleCancel = () => {
  modalVisible.value = false;
  resetForm();
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    type: '',
    description: '',
    customerCurrency: 'CNY',
    customerBasePrice: 0,
    customerUnit: 'month',
    platformCost: 0,
    platformMargin: 0,
    platformRevenueShare: 0.3,
  });
};

// 生命周期
onMounted(() => {
  loadPricingList();
});
</script>

<style lang="less" scoped>
.pricing-center {
  padding: 24px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h2 {
      margin: 0;
    }
  }

  .price {
    font-weight: bold;
    color: #1890ff;
  }

  .text-danger {
    color: #ff4d4f;
  }
}
</style>
